
/**
 * 基础信息定义
 */
const env = 'prod'; 
if(env == 'local'){
    var BaseUrl = 'http://localhost';
    var HostUrl = 'http://localhost:81';
}
if(env == 'prod'){
    var BaseUrl = 'http://api.xiaomashengxian.com';
    var HostUrl = 'http://www.xiaomashengxian.com';
   // var HostUrl =  window.location.protocol+'//'+window.location.host; 
}

/**
 * 外部全局方法定义
 */
var global = function(){

  	//接口api	 	
  	this.BaseUrl = '';
  	this.HostUrl = '';

    //用户基本信息
    this.dataParam = function(temp){

	    var user = []; 
	    user['uid']   = this.getCookie('uid');
	    user['time']  = this.getCookie('time');
	    user['token'] = this.getCookie('token');

	    //追加参数
	    if(temp){
	        for(var i in temp){
	           user[i]   = temp[i];
	        }
	    }
	    var Param = this.parseParam(user);
	    return Param;
	}


	//url转换
	this.parseParam = function(param, key, encode) {  

		  if(param==null) return '';  
		  var paramStr = '';  
		  var t = typeof(param);  

		  if(t == 'string' || t == 'number' || t == 'boolean')
			{  
			    paramStr += '&' + key + '=' + ((encode==null||encode) ? encodeURIComponent(param) : param);  
			}else{  
			    for(var i in param) {  
			      var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);  
			      paramStr += this.parseParam(param[i], k, encode);  
			    }  
			}

		  return paramStr;  
	};


	//写Cookie
	this.setCookie = function(cname, cvalue, exdays,path,domain) {
		var d = new Date();
			d.setTime(d.getTime() + (exdays * 60 * 60 * 1000));

		var expires = "expires=" + d.toUTCString();
		document.cookie = cname + "=" + cvalue + "; " + expires+
	        			((path) ?  "; path=" + path : "; path=/")+
	        			((domain) ? "; domain=" + domain : "");
	}


	//读Cookie
	this.getCookie = function(cname) {
		var name = cname + "=";
		var ca = document.cookie.split(';');

		for (var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1);
			if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
		}

		return "";
	}	


	//读取url参数
	this.getQueryString = function(name)
	{
	     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	     var r = window.location.search.substr(1).match(reg);
	     if(r!=null)return  unescape(r[2]); return null;
	}


	//判断是否微信浏览器
    this.isWeiXin = function(){
      var ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
          return true;
      } else {
          return false;
      }
    }


	//异常输出
	this.center_error = function(data){
	  	alert(data.msg);        
	}

	//获取url
	this.getUrl = function(mode){
		if(mode == 1){
		    return window.location.pathname.toString();
		}else{
			return location.href.toString();
		}
	}
	
	//加参数	
	this.ChangeParam = function(name,value){
      var Url=  window.location.href ;
      var reg = new RegExp("(^|)"+ name +"=([^&]*)(|$)");
      var tmp = name + "=" + value;

      if(Url.match(reg) != null)
      {
          newUrl= Url.replace(eval(reg),tmp);
      }
      else
      {
         if(Url.match("[\?]"))
         {
         newUrl= Url + "&" + tmp;
         }
         else
         {
         newUrl= Url + "?" + tmp;
         }
      }
      return newUrl;
   }

}



//分享信息
var share  = function(global){
 	
 	//类型
 	this.type = 'activity';

	//是否展示微信分享
	this.onReady = function(){
	    if(global.isWeiXin()){
	       if(!global.getCookie('uid') && !global.getCookie('time') && !global.getCookie('token')){
	           wx.hideOptionMenu();
	       }else{
	           wx.showOptionMenu();
	       }
	    }
	}


    //分享初始化
    this.share_init =  function(arr){

    	 if(!global.isWeiXin()){
    	 	console.log('非微信浏览器环境');
    	 	return false;
    	 }

        var url      = global.HostUrl+'/php/v1/wxjsApi.php?mode=Wxshare'; 
        var Data     = global.dataParam(arr);

        $.ajax({
           type: "POST",
           url: url,
           async: false,
           data: Data,
           success: function(temp){ 
            if(temp.code == 200){ 
            	var conf = temp.data;
            	//初始化
               	wx.config({
			        debug:false,
			        appId:conf.appId,
			        timestamp:conf.timestamp,
			        nonceStr:conf.nonceStr,
			        signature:conf.signature,
			        jsApiList: [
			          'checkJsApi',
			          'onMenuShareAppMessage',//朋友
			          'onMenuShareTimeline',  //朋友圈  
			          'onMenuShareQQ',        //QQ
			          'onMenuShareQZone',     //QQ空间
			        ]
			   });
               wx.error(function(res) {
               		window.location.href = location.href.split('#')[0];

					/*
				    let wx_num = parseint(global.getCookie('wx_num'));alert(wx_num);
					if(!wx_num){
						 global.setCookie('wx_num',1);
						 window.location.href = location.href.split('#')[0];
					}else{
						 alert('服务异常,请联系客服');
					}*/
					
				});
               
            }else{
                global.center_error(temp);        
            }  
           }
        });
    }


	//分享记录	
   this.share_on =  function(link,token,note){
        if(!link){
          alert('分享链接异常，无效');
          return;
        }

        var arr = [];
        arr['type']  = this.type;
        arr['url']   = link;
        arr['code']  = token;
        arr['note']  = note;

        if(this.type == 'activity'){
        	var id = $("#goods_id").html();
        	if(!id){
        		id = $(".goods_id").first().html();
        	}
        	
        	arr['id']   = id;
	    }else{
	    	arr['id']   = '';
	    }

	  	var url  =  global.BaseUrl+'/mobile/api/v1/Source.php?mode=share_on';
	    	url  += global.dataParam(arr);

	    $.ajax({
	         type: "GET",
	         async: true,
	         url: url,
	         dataType: "jsonp",
		     jsonp: "callback",
		     jsonpCallback: "jsoncallback",
	         success: function(temp){
	           	 if(temp.code != 200){
	               	global.center_error(temp);        
	               	return false;
	          	  }  
	         },
	      	 error:function(jqXHR2, textStatus, errorThrown) {
	            alert('分享异常!');
	            alert(errorThrown);
		      }
	     });

    }


   //分享回流	
   this.share_guest =  function(){
        var code   = global.getQueryString('sharetoken');

        //分享回流
        if(code){
            var arr = [];
            arr['url'] 	  = global.getUrl(1);
	        arr['code']   = code;

		  	var url  =  global.BaseUrl+'/mobile/api/v1/Source.php?mode=share_back_on';
		    	url  += global.dataParam(arr);

		    $.ajax({
		         type: "get",
		         async: true,
		         url: url,
		         dataType: "jsonp",
			     jsonp: "callback",
			     jsonpCallback: "jsoncallback",
		         success: function(temp){
		            if(temp.code != 200){
		               global.center_error(temp);        
		            }
	           }
	        });
        }
    }

    //微信分享
    this.share_wx = function(info){
    	 let that = this;
     	 wx.ready(function(){ 
	        //朋友圈
	        wx.onMenuShareTimeline({title: info.title, link:info.link,imgUrl:info.imgUrl,
	              success:function (res){ that.share_on(info.link,info.token,'Timeline');},  
	              cancel: function (res){ console.log('shared cancel');},  
	              fail: function (res) {  console.log(JSON.stringify(res));}  
	        });
	        //朋友
	        wx.onMenuShareAppMessage({title:info.title,desc:info.desc,link:info.link,imgUrl:info.imgUrl,type: info.type,dataUrl:info.dataUrl,
	              success:function (res){that.share_on(info.link,info.token,'AppMessage');},  
	              cancel: function (res){ console.log('shared cancel');},  
	              fail: function (res) {  console.log(JSON.stringify(res));}  
	        });
	        //分享到QQ
	        wx.onMenuShareQQ({ title: info.title,desc:  info.desc, link:  info.link, imgUrl:info.imgUrl,
	              success:function (res){ that.share_on(info.link,info.token,'QQ');},  
	              cancel: function (res){ console.log('shared cancel');},  
	              fail: function (res) {  console.log(JSON.stringify(res));}  
	        });
	        //分享到QQ空间
	        wx.onMenuShareQZone({title: info.title,desc:  info.desc,link:  info.link, imgUrl:info.imgUrl,
	              success:function (res){ that.share_on(info.link,info.token,'QZone');},  
	              cancel: function (res){ console.log('shared cancel');},  
	              fail: function (res) {  console.log(JSON.stringify(res));}  
	        });  
	        //qq微博 
	        wx.onMenuShareWeibo({title: info.title,desc:  info.desc,link:  info.link, imgUrl:info.imgUrl,
	             success:function (res){ that.share_on(info.link,info.token,'Weibo');},  
	              cancel: function (res){ console.log('shared cancel');},  
	              fail: function (res) {  console.log(JSON.stringify(res));}  
	        });
 		}); 
    },

 	//页面分享内容
 	this.share_web =  function(info){
 	   let that = this;
       mobShare.config( {
            debug: true,
            params: {
                url: info.link,
                title: info.title, 
                description: info.desc,
                pic: info.imgUrl,
            },
            callback:function(plat,params) {
                that.share_on(info.link,info.token,plat)  
            }
	    });
	 }

}


//初始化
var init = new global();
init.BaseUrl = BaseUrl;
init.HostUrl = HostUrl;


init.setCookie('uid', 16);
init.setCookie('time', 1513850795);
init.setCookie('token', '8373e2c3614d9148bf97a12557e38e87');


/*init.setCookie('uid', 38);
init.setCookie('time', 1514166248);
init.setCookie('token', 'f9a163b6512fc1ba89db836d8562eae7');*/


var share  = new share(init);
